<?php

namespace App\Services\Goods\Traits;

use App\Services\Manage\ManageIndex;
trait OperateAppCate
{
	/**
     * @author:      李颖
     * @DateTime:    2017-09-29 14:05:25
     * @Description: 操作分类 该分类的结构： app_id other_app_read is_public pid
     * @Description: 该种分类相似的不少 避免在逻辑层粘贴复制大量代码 故写为traits
     */
    

	/*获取某个分类详情 不删除的便可*/
    private function _oneCateInfo(array $data, $Model, array $otherMap = []): array 
    {
        $_where[] = ['id','=',$data['id']];
        $_where[] = isset($otherMap['status']) ? ['status','=',$otherMap['status']] : ['status','<>',-1];
        $que=$Model->where($_where);
        if (isset($data['app_id'])) {   //若卖家查看商品详情，则不传入app_id
            $manageAppId = ManageIndex::Api()->getAppId();
            $app_id = $data['app_id'];

            if ($manageAppId != $data['app_id']) {
                $que->Where(function ($query) use ($app_id) {
                    $query->where('app_id', $app_id)->orWhere(function ($query) use ($app_id) {
                        $query->whereRaw("FIND_IN_SET($app_id,`other_app_read`)");
                    })->orWhere('is_public', 1);
                });
            }
        }
        $res = $que->first();
        return auto_return($res);
    }

    /*后台删除某个分类*/
    private function _delOneCate(array $data, $Model): array 
    {
        //判断是否存在子类
        $_findChild[] = ['pid','=',$data['id']];
        $_findChild[] = ['status','<>','-1'];
        $que=$Model->where($_findChild);
        $manageAppId = ManageIndex::Api()->getAppId();
        $app_id = $data['app_id'];
        if ($manageAppId != $data['app_id']) {
            $que->Where(function ($query) use ($app_id) {
                $query->where('app_id', $app_id)->orWhere(function ($query) use ($app_id) {
                    $query->whereRaw("FIND_IN_SET($app_id,`other_app_read`)");
                })->orWhere('is_public', 1);
            });
        }

        $childList = $que->get()->toArray();
        if($childList){
            return verify_err($childList, '该分类下存在子类[' . $childList[0]['name'] . ']，不可删除');
        }

        $_where[] = ['id','=',$data['id']];
        $_where[] = ['status','<>','-1'];
        $data['app_id'] != $manageAppId && $_where[] = ['app_id','=',$data['app_id']];

        $res = $Model->where($_where)->update(['status'=>-1]);
        return $res ? auto_success($res, '成功删除该分类') : verify_err($res, '此分类已删除或不属于该应用');
    }
}